//
//  CurrentUser.m
//

#import "CurrentUser.h"
#import "NetDataCacheManager.h"

@implementation CurrentUser

static CurrentUser *_currentUser = nil;

+ (instancetype)mine{
    if (nil == _currentUser) {
        _currentUser=[[super alloc] initMine];
    }
    return _currentUser;
}

- (NSString *)sessionKey{
    if(!_sessionKey)
        return @"";
    return _sessionKey;
}

- (instancetype)initMine{
    
    self = [super init];
    if (self) {
        
        NSString * sessionKey = [[NSUserDefaults standardUserDefaults] objectForKey:kUserSessionKey_Mine];
        
        if(ESIsStringWithAnyText(sessionKey)){
            self.sessionKey = sessionKey;
        }
        
    }
    return self;
}

- (void)reset{
    if (_currentUser) {
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserSessionKey_Mine];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kOrderNumber];
        
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationMsg_Exit_Success object:nil];
        
        /* Clear cookies */
        [CreditCore deleteAllHTTPCookies];
        [NetDataCacheManager resetCache];
        _currentUser = nil;
        [[self class] mine];
    }
}


MJExtensionCodingImplementation
- (void)save{
    ESWeak(self, _self);
    ESDispatchOnBackgroundQueue(^{
        [NSThread sleepForTimeInterval:0.50f];
        
        [[NSUserDefaults standardUserDefaults] setObject:_self.sessionKey forKey:kUserSessionKey_Mine];
    });
}


+ (void)loginSuccess:(NSString *)sessionKey{
    [NetDataCacheManager resetCache];
    [[CurrentUser mine] setSessionKey:sessionKey];
    [[CurrentUser mine] save];
}

- (BOOL)hasLogged{
    if (ESIsStringWithAnyText(self.sessionKey)) {
        return YES;
    }
    return NO;
}

+ (void)userLogoutSuccess:(SuccessBlock)success failure:(FailureBlock)failure{
    
    [[CurrentUser mine] reset];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationMsg_Exit_Success object:nil];
    success(nil);
    
    /*
     [CreditServerHelper logoutSuccess:^(id response) {
     [[CurrentUser mine] reset];
     [[NSNotificationCenter defaultCenter] postNotificationName:NotificationMsg_Exit_Success object:nil];
     success(nil);
     } failure:^(NSError *error) {
     [[CurrentUser mine] reset];
     [[NSNotificationCenter defaultCenter] postNotificationName:NotificationMsg_Exit_Success object:nil];
     success(nil);
     }];
     */
    
}

@synthesize userInfo = _userInfo;

- (UserInfoModel *)userInfo {
    if (!_userInfo) {
        if ([[CurrentUser mine] hasLogged]) {
            id data = [Utility getDataWithKey:kDefaultUserInfoKey];
            if (data) {
                UserInfoModel *tmpUser = (UserInfoModel *)[NSKeyedUnarchiver unarchivedObjectOfClass:NSDictionary.class fromData:data error:nil];
                NSString *mobile = tmpUser.phone;
                NSString *userMobile = [[NSUserDefaults standardUserDefaults] valueForKey:kUserNameKey];
                if ([mobile isEqualToString:userMobile]) {
                    _userInfo = tmpUser;
                }
            }
        }
    }
    return _userInfo;
}

- (void)setUserInfo:(UserInfoModel *)userInfo {
    if (_userInfo != userInfo) {
        _userInfo = userInfo;
        id data = [NSKeyedArchiver archivedDataWithRootObject:_userInfo requiringSecureCoding:false error:nil];
        [Utility saveDataWithKey:kDefaultUserInfoKey ofValue:data];
    }
}

+ (BOOL)setUserInfoWithDic:(NSDictionary *)userInfo{
    if(![[CurrentUser mine] hasLogged])
        return NO;
    [CurrentUser mine].userInfo = [UserInfoModel mj_objectWithKeyValues:userInfo];
    return YES;
}


@end

